<?php

// +----------------------------------------------------------------------
// | ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014-2018 东莞市云拓互联网络科技有限公司
// +----------------------------------------------------------------------
// | 官方网站:http://www.ytclouds.net
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// |
// +----------------------------------------------------------------------

namespace app\lottery\controller;

use controller\BasicAdmin;
use service\DataService;
use service\LogService;
use think\Db;
use service\WechatService;
use think\Exception;
use \think\File;

/**
 * 应用入口控制器
 * @author Anyon <zoujingli@qq.com>
 */
class Index extends BasicAdmin
{

    /**
     * 定义当前操作表名
     * @var string
     */
    public $table = 'LotteryConfig';
    public $table_form = 'LotteryPool';

    /**
     * 普通抽奖配置
     * @return mixed
     */
    public function index()
    {
        $this->title = '普通抽奖配置';
        $this->assign("title", $this->title);
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $post['id'] = 1;
            DataService::save($this->table, $post, 'id');
            LogService::write('抽奖配置', '抽奖配置成功');
            $this->success('抽奖配置成功！', '');
        }
        $lottery_config = Db::name($this->table)->find();
        $this->assign('lottery_config', $lottery_config);
        return $this->fetch('');
    }

    /**
     * 高级抽奖设置
     * @return mixed
     */
    public function high_lottery_set()
    {
        $this->title = '高级抽奖配置';
        $this->assign("title", $this->title);
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $post['id'] = 2;
            DataService::save($this->table, $post, 'id');
            LogService::write('抽奖配置', '高级抽奖配置成功');
            $this->success('抽奖配置成功！', '');
        }
        $lottery_config = Db::name($this->table)->where(['id' => 2])->find();
        $this->assign('lottery_config', $lottery_config);
        return $this->fetch('');
    }

    /**
     * 普通抽奖奖池列表
     */
    public function lottery_pool_list()
    {
        $get = $this->request->get();
        $type = isset($get['type']) ? $get['type'] : 0;
        $list = Db::name($this->table_form)
            ->where(['type' => $type, 'is_deleted' => 0])
            ->select();
        $this->title = $type ? '高级奖品列表' : '普通奖品列表';
        //被抽走的数量
        foreach ($list as $k => &$v){
            if($v['goods_name'] != '谢谢惠顾'){
                $v['lottery_num'] = Db::name("LotteryCdkey")
                    ->where(["lottery_pool_id"=>$v['id'],'is_used'=>1])
                    ->count();
            }else{
                $v['lottery_num'] = 0;
            }
        }
        $this->assign("title", $this->title);
        $this->assign("type", $type);
        $this->assign("list", $list);
        return $this->fetch('');
    }

    /**
     * 普通抽奖奖池列表
     */
    public function high_lottery_pool_list()
    {
        $get = $this->request->get();
        $type = isset($get['type']) ? $get['type'] : 1;
        $list = Db::name($this->table_form)
            ->where(['type' => $type, 'is_deleted' => 0])
            ->select();
        $this->title = $type ? '高级奖品列表' : '普通奖品列表';
        //被抽走的数量
        foreach ($list as $k => &$v){
            if($v['goods_name'] != '谢谢惠顾'){
                $v['lottery_num'] = Db::name("LotteryCdkey")
                    ->where(["lottery_pool_id"=>$v['id'],'is_used'=>1])
                    ->count();
            }else{
                $v['lottery_num'] = 0;
            }
        }
        $this->assign("title", $this->title);
        $this->assign("type", $type);
        $this->assign("list", $list);
        return $this->fetch('lottery_pool_list');
    }



    /**
     * 表单数据处理
     * @param array $vo
     */
    protected function _form_filter(&$vo)
    {
        if ($this->request->isPost()) {
            if (!$this->request->post("id")) {
                $vo['addtime'] = time();
            }
            $post = $this->request->post();
            if (isset($post['href']) && $post['href'] != '' && strpos($post['href'], "http") === false) {
                $vo['href'] = 'http://' . $post['href'];
            }
        }
    }

    /**
     * 奖品添加
     * @return array|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\Exception
     */
    public function add()
    {
        $get = $this->request->get();
        $type = isset($get['type']) ? $get['type'] : 0;
        $this->assign("type", $type);
        return $this->_form($this->table_form, 'form');
    }

    /**
     * 奖品编辑
     * @return array|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\Exception
     */
    public function edit()
    {
        $get = $this->request->get();
        $type = isset($get['type']) ? $get['type'] : 0;
        $this->assign("type", $type);
        return $this->_form($this->table_form, 'form');
    }

    /**
     * 奖品禁用
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function forbid()
    {
        if (DataService::update($this->table_form)) {
            LogService::write('抽奖配置', 'ID ' . $this->request->request("id") . ' 奖品禁用成功');
            $this->success("奖品禁用成功！", '');
        }
        $this->error("奖品禁用失败，请稍候再试！");
    }

    /**
     * 奖品禁用
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function resume()
    {
        if (DataService::update($this->table_form)) {
            LogService::write('抽奖配置', 'ID ' . $this->request->request("id") . ' 奖品启用成功');
            $this->success("奖品启用成功！", '');
        }
        $this->error("奖品启用失败，请稍候再试！");
    }

    public function txt()
    {
        $upload_txt = 'http://lottery.com/static/upload/ea7ed60db3434ff9/c93c67571fb415b5.txt';
        $upload_txt = explode('/static', $upload_txt);
        $upload_txt = './static' . $upload_txt[1];
        $file = new \SplFileObject($upload_txt);
        $cdkeys = [];
        while ($file->current() != '') {
            $cdkeys[] = $file->current();
            $file->next();
        }
    }

    /**
     * 导入CDkey
     */
    public function improt_cdk()
    {
        if ($this->request->isPost()) {
            set_time_limit(0);
            $post = $this->request->post();
            $id = isset($post['id']) ? $post['id'] : 0;
            if (!$id) {
                $this->error("缺少参数，请稍后重试");
            }
            $nowtime = time();
            $upload_txt = isset($post['upload_txt']) ? $post['upload_txt'] : '';
            if ($upload_txt == '' || strpos($upload_txt, '.txt') === false) {
                $this->error("请上传txt文件");
            }
            $upload_txt = explode('/static', $upload_txt);
            $upload_txt = './static' . $upload_txt[1];
            $file = new \SplFileObject($upload_txt);

            $insert_sql = "INSERT INTO `lottery_cdkey` (`lottery_pool_id`, `cdkey`, `add_time`) VALUES ";
            $i = 0;
            while ($file->current() != '') {
                $insert_sql .= " ('{$id}','{$file->current()}','{$nowtime}'),";
                $i++;
                $file->next();
            }

            if ($i == 0) {
                $this->error("无数据");
            }
            $insert_sql = trim($insert_sql,',');

            try{
                $r = Db::execute($insert_sql);
                if ($r) {
                    $new_count = Db::name("LotteryCdkey")->where(['lottery_pool_id'=>$id])->count();
                    Db::name("LotteryPool")
                        ->where(['id'=>$id])
                        ->data(['goods_num'=>$new_count])
                        ->update();
                    $this->success("保存成功");
                } else {
                    $this->error("保存失败");
                }
            }catch (Exception $e){
                $error_code = $e->getCode();
                if($error_code == 10501){
                    $this->error("上传的CDKey和数据库里的包含重复");
                }else{
                    $this->error($e->getMessage());
                }
            }
            exit;
        }
        $get = $this->request->get();
        $id = isset($get['id']) ? $get['id'] : 0;
        if (!$id) {
            $this->error("缺少参数，请稍后重试");
        }
        $info = Db::name($this->table_form)
            ->where(["id" => $id])
            ->find();

        return $this->fetch("improt_cdk", ['id' => $id, 'vo' => $info]);
    }


    /**
     * 删除奖品
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function del()
    {
        if (DataService::update($this->table_form)) {
            LogService::write('抽奖配置', 'ID ' . $this->request->request("id") . ' 奖品删除');
            $this->success("奖品删除成功！", '');
        }
        $this->error("奖品删除失败，请稍候再试！");
    }




}
